package com.zhongshengnetwork.rightbe.wzt.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.ClassifyAuthInfoModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.lang.activity.UserLangActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ClassifyAuthRequestActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private TopBarView topbar;
    private RelativeLayout ordertype_layout;
    private TextView ordertype;
    private int orderType = 0;

    private List<ClassifyAuthInfoModel> list;
    private ListView listview;

    private int pageindex = 0;
    private static final int Records = 20;
    private boolean isHasMore = false;
    List<String> nameList = null;
    private RefreshLayout mRefreshLayout;
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify_auth_request);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        topbar.getTitleView().setClickable(true);
        topbar.getTitleView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (list != null && list.size() > 0){
                    //listview.smoothScrollToPosition(0);
                    listview.setSelection(0);
                }
            }
        });

        ordertype_layout = (RelativeLayout) findViewById(R.id.ordertype_layout);
        ordertype_layout.setClickable(true);
        ordertype_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMenu();
            }
        });
        ordertype = (TextView) findViewById(R.id.ordertype);

        pageindex = 0;
        if (list == null){
            list = new ArrayList<ClassifyAuthInfoModel>();
        }
        listview=(ListView) findViewById(R.id.classify_auth_listview);
        adapter=new MyAdapter();
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (list == null || list.size() == 0){
                    return;
                }
                Log.e("TAG","position="+i);
                int index = i;// - 1;
                while (index < 0){//解决部分手机点击第一条不是从1开始的问题
                    index+=1;
                }
                ClassifyAuthInfoModel model = list.get(index);
                Intent intent = new Intent(ClassifyAuthRequestActivity.this, UserLangActivity.class);
                intent.putExtra(APIKey.useridKey,model.getUserid());
                intent.putExtra(APIKey.typeKey,1);
                intent.putExtra(APIKey.titleKey,model.getNickname());
                startActivity(intent);
            }
        });

        mRefreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        //设置 Header 为 贝塞尔雷达 样式
        mRefreshLayout.setRefreshHeader(new BezierRadarHeader(ClassifyAuthRequestActivity.this).setEnableHorizontalDrag(true));//BezierRadarHeader
        //设置 Footer 为 球脉冲 样式
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(ClassifyAuthRequestActivity.this).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
        mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
        mRefreshLayout.setEnableRefresh(true);//启用刷新
        mRefreshLayout.setEnableLoadMore(true);//启用加载
        //刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //refreshlayout.finishRefresh();
                pageindex = 0;
                getData();
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //refreshLayout.finishLoadMore();
                getData();
            }
        });
        mRefreshLayout.autoRefresh(100,300,1f,false);

    }

    private void getData(){
        if (listview == null){
            return;
        }
        new Thread(){
            @Override
            public void run() {
                super.run();
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                map.put("dataStatus",""+orderType);
                HttpsUtils.miniAppDo(map, "weishu/classify/request/list.do", new HttpCallBack() {
                    @Override
                    public void onSuccess(final String data) {
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<ClassifyAuthInfoModel> l = GsonTools.getClassifyAuthInfoModel(data);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        list.clear();
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    if (l != null && l.size() > 0){
                                        if (l.size() >= Records){
                                            //listview.setPullLoadEnable(true);
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            //listview.setPullLoadEnable(false);
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        list.addAll(l);
                                    }else {
                                        //listview.setPullLoadEnable(false);
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    pageindex += 1;
                                    adapter.notifyDataSetChanged();
                                }
                            });

                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    CustomApplication.showTip(commonModel, ClassifyAuthRequestActivity.this);
                                }
                            });

                        }
                    }

                    @Override
                    public void onError(String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mRefreshLayout.getState() == RefreshState.Loading){
                                    //listview.stopLoadMore();
                                    mRefreshLayout.finishLoadMore();
                                }else {
                                    //listview.stopRefresh(true);
                                    mRefreshLayout.finishRefresh();
                                }
                            }
                        });
                    }
                });
            }
        }.start();

    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LangDetailActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void showMenu(){
        if (nameList == null){
            nameList = new ArrayList<String>();
            nameList.add("未同意");
            nameList.add("已同意");
            nameList.add("已拒绝");
        }
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(ClassifyAuthRequestActivity.this)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : nameList){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which > 0){
                        String title = nameList.get(which-1);
                        orderType = which - 1;
                        ordertype.setText(title);
                        if (mRefreshLayout != null){
                            Log.e("TAG","进来获取数据了刷新界面");
                            pageindex = 0;
                            mRefreshLayout.autoRefresh(100,300,1f,false);
                        }
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(ClassifyAuthRequestActivity.this, R.layout.classify_auth_item,null);
            }
            View view=convertView;
            //view = LayoutInflater.from(getActivity()).inflate(R.layout.lang_circle_item, null);
            ImageView lang_circle_header = (ImageView) view.findViewById(R.id.lang_circle_header);
            ImageView privateIcon = (ImageView) view.findViewById(R.id.private_icon);
            TextView lang_circle_nickname = (TextView) view.findViewById(R.id.lang_circle_nickname);
            Button lang_circle_care = (Button) view.findViewById(R.id.lang_circle_care);
            TextView detail = (TextView) view.findViewById(R.id.detail);
            ClassifyAuthInfoModel model = list.get(position);

            try {
                Glide.with(ClassifyAuthRequestActivity.this).load(model.getHeader()).transform(new CircleTransform(ClassifyAuthRequestActivity.this)).dontAnimate().into(lang_circle_header);
            }catch (Exception e){
                LangPublishActivity.uploadError("分类授权列表加载图片报错："+e.getLocalizedMessage());
            }
            privateIcon.setVisibility(View.GONE);
            lang_circle_nickname.setText(model.getNickname());
            lang_circle_care.setTag(position);
            lang_circle_care.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onClickCare((int) view.getTag());
                }
            });
            lang_circle_care.setVisibility(View.VISIBLE);
            lang_circle_care.setTextColor(Color.parseColor("#C0C0C0"));
            if (model.getAuthStatus() == 0){
                lang_circle_care.setText("同意");
                lang_circle_care.setTextColor(Color.parseColor("#87cefa"));
            }else if(model.getAuthStatus() == 1){
                lang_circle_care.setText("已同意");
            }else if (model.getAuthStatus() == 2){
                lang_circle_care.setText("已拒绝");
            }

            detail.setText(model.getAuthText());

            ImageView lang_member_icon = (ImageView) view.findViewById(R.id.lang_member_icon);
            if (!CommonUtils.isEmpty(model.getMemberIcon())){
                lang_member_icon.setVisibility(View.VISIBLE);
                try{
                    Glide.with(ClassifyAuthRequestActivity.this).load(model.getMemberIcon()).
                            diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(lang_member_icon);
                }catch (Exception e){
                    LangPublishActivity.uploadError("智慧排行点赞列表加载图片报错："+e.getLocalizedMessage());
                }

            }else {
                lang_member_icon.setVisibility(View.INVISIBLE);
            }

            return view;
        }

    }

    //点击关注
    private void onClickCare(final int position){
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(ClassifyAuthRequestActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }
        final ClassifyAuthInfoModel model = list.get(position);

        String msg = "确定同意#"+model.getNickname()+"#查看分类《"+model.getClassifyName()+"》？";
        if (model.getAuthStatus() == 2){
            msg = "你已拒绝#"+model.getNickname()+"#查看分类《"+model.getClassifyName()+"》，确定同意对方查看吗？";
        }else if (model.getAuthStatus() == 1){
            msg = "你已同意#"+model.getNickname()+"#查看分类《"+model.getClassifyName()+"》，确定禁止对方查看吗？";
        }

        final CustomDialog.Builder builder = new CustomDialog.Builder(ClassifyAuthRequestActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage(msg);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                KyLoadingBuilder d = new KyLoadingBuilder(ClassifyAuthRequestActivity.this);
                d.setIcon(R.drawable.loading04);
                d.setText("正在处理...");
                d.setOutsideTouchable(false);//点击空白区域是否关闭
                d.setBackTouchable(true);//按返回键是否关闭
                d.show();
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                map.put("dataId", model.getClassifyId()+"");
                map.put("dataUserId",model.getUserid());
                if (model.getAuthStatus() == 1){
                    map.put("dataStatus","0");
                }else {
                    map.put("dataStatus","1");
                }
                String url = "weishu/classify/check/auth.do";
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                d.dismiss();
                                CommonModel commonModel = GsonTools.getCommonModel(data);
                                if (commonModel.getFlag().equals("1")){
                                    ToastUtil.show(ClassifyAuthRequestActivity.this, "处理成功");
                                    if (model.getAuthStatus() == 0 || model.getAuthStatus() == 2){
                                        Byte status = 1;
                                        model.setAuthStatus(status);
                                    }else {
                                        Byte status = 2;
                                        model.setAuthStatus(status);
                                    }
                                    adapter.notifyDataSetChanged();
                                }else {
                                    ToastUtil.show(ClassifyAuthRequestActivity.this, commonModel.getMsg());
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                d.dismiss();
                                ToastUtil.show(ClassifyAuthRequestActivity.this, "提交失败");
                            }
                        });
                    }
                });
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        CustomDialog dialog = builder.create();
        dialog.show();


    }

}
